package com.itheima.common;

import com.itheima.pojo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry '财务部' for key 'dept.name'
        if(ex.getMessage().contains("Duplicate entry")){
            String msg=ex.getMessage().split(" ")[2]+"部门已存在";
            return Result.error(msg);
        }
        return Result.error("未知异常错误");
    }
}
